
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import text
import json
from ..database import get_db

router = APIRouter(
    prefix="/api/v1/communities",
    tags=["Communities"],
)

@router.get("") # 路径现在是空的，因为 prefix 已经定义了
def get_all_communities(db: Session = Depends(get_db)):
    """
    获取所有社区（74个区域）的地理边界、中心点和基本信息。
    """
    query = text("""
        SELECT 
            id, name, district, 
            area_sqkm_approx AS area_sqkm,
            ST_AsGeoJSON(geometry) AS geometry,
            ST_X(ST_Centroid(geometry)) AS center_lng,
            ST_Y(ST_Centroid(geometry)) AS center_lat
        FROM communities;
    """)
    
    result = db.execute(query)
    
    communities = []
    for row in result:
        row_dict = dict(row._mapping)
        row_dict['geometry'] = json.loads(row_dict['geometry'])
        communities.append(row_dict)
        
    return {
        "code": 0,
        "message": "success",
        "data": communities
    }